<?php

namespace catchAdmin\api\controller;

use cainiao\api\v1\Link;
use catchAdmin\customs\model\HnOrder;
use catchAdmin\customs\model\HnOrderDetail;
use catchAdmin\customs\model\OrderSon;
use catchAdmin\externalGoods\model\GoodsAttribute;
use catchAdmin\externalGoods\model\GoodsRule as externalGoodsRuleModel;
use catchAdmin\externalGoods\model\OrderLogistics;
use catchAdmin\externalGoods\model\TenantGoods;
use catcher\CatchAuth;
use catcher\CatchResponse;
use catcher\Code;
use houniao\api\v1\Order as HNOrderApi;
use thans\jwt\facade\JWTAuth;
use think\Exception;
use think\facade\Db;
use think\helper\Str;
use think\Request;
use think\facade\Request as ThinkRequest;
/*
 *
 * */
class Order extends Index
{
    public function goodsService(Request $request)
    {
        try {
            //获取参数
            $serviceType = $request->param('serviceType');
            $data = $request->post('data');
            //var_dump(file_get_contents('php://input')); //接受row数据
            //写入日志处理
            $this->writeLog('HouNiao',json_encode($data,JSON_UNESCAPED_UNICODE));

            //验证token
            $auth = JWTAuth::auth();
            $this->merchantInfo = json_decode(json_encode($auth['merchantInfo']),true);//验证token


//            if(!$request->has('data','post')){
//                return $this->commonReturn('goods',['code'=>Code::FAILED, 'msg'=>'缺少data']);
//            }
//
//            //处理data
//            $data = json_decode($data,true);
//            if(!$data||!is_array($data)){
//                return $this->commonReturn('goods',['code'=>Code::FAILED, 'msg'=>'data格式错误']);
//            }

            //方法分发
            switch ($serviceType)
            {
                //接收订单
                case 'cancel':
                    $result = $this->cancel();
                    break;
                case 'after_sale_detail':
                    $result = $this->after_sale_detail();
                    break;
                case 'get_info':
                    $result = $this->get_info();
                    break;
                default:
                    $result = ['code'=>Code::FAILED, 'msg'=>'未定义的服务'];
            }

            return $this->commonReturn("HouNiao:" . $serviceType,$result);

        } catch (\Exception $exception) {
            return $this->commonReturn("HouNiao:" . $serviceType,['code'=>Code::FAILED, 'msg'=>$exception->getMessage()]);

        }

    }

    protected function get_info(){
        $request = (new ThinkRequest);
        $params =  $request::post();
        $hnOrderDetailModel = new HnOrderDetail;
        $hnOrderModel = new \catchAdmin\customs\model\Order;
        $externalGoodsRuleModel = new externalGoodsRuleModel;
        $logisticsModel = new OrderLogistics;

        $tenant_id = $this->merchantInfo['tenant_id'];

        //dd($params);
        //$order_id = $params['order_id'] ?? '';
        $source_order_no = $params['source_order_no'] ?? '';

        $order_pk = $hnOrderModel->where('tenant_id',$this->merchantInfo['tenant_id'])
            ->where('orderId',$source_order_no)->value('id');

        $order_nos = $hnOrderDetailModel
            ->where('tenant_id',$this->merchantInfo['tenant_id'])
            ->where('order_id',$order_pk)->column('order_no');

        if(empty($order_nos))  return [ 'code'=>Code::FAILED , 'msg'=> '订单不存在或未完成推单'];

        $return = [];

        if($order_pk > 116274){
            //新的
            $orderListResult = (new OrderSon)->where('orderId',$source_order_no)->select();
            if (!$orderListResult) {
                $orderListResult = [];
            }else{
                $orderListResult =  $orderListResult->toArray();
            }

            try {

                foreach ($orderListResult as $_order){
//                    $hnInfo = $hnOrderDetailModel->where([
//                        'source_order_no'=>$_order['orderlistId'],
//                    ])->find();

                    //同一个订单会拆单
                    $hnInfo_arr = $hnOrderDetailModel->where([
                        'source_order_no'=>$_order['orderlistId'],
                    ])->select();

//                    dd($hnInfo);

                    if(!$hnInfo_arr) continue;
                    $hnInfo_arr = $hnInfo_arr->toArray();

                    foreach ($hnInfo_arr as $hnInfo){
                        $mainOrderInfo = (new \catchAdmin\customs\model\Order)->where('orderId',$_order['orderId'])->find();

                        $_data  = [
                            "order_id"=>'' ,
                            "order_no"=>$hnInfo['order_no'],
                            "source_order_no"=>$_order['orderId'],
                            "username"=>$mainOrderInfo['contactName'],
                            "phone"=> $mainOrderInfo['contactMobile'],
                            "id_card"=> "",
                            "id_card_back_img"=>"",
                            "id_card_front_img"=> "",
                            "associated_path"=> $mainOrderInfo['contactAddr'],
                            "address"=> $mainOrderInfo['detailAddr'],
//                        "customs_time"=> time(),
//                        "delivery_time"=> time(),
                            "customs_time"=> 0,
                            "delivery_time"=> 0,
                            "receive_time"=> 0,
                            "cancel_order_time"=> 0,
                            "cancel_reason"=> null,
                            "except_reason"=>null,
                            "is_refund"=>0,
                            "refund_type"=> 0,
                            "goods_money"=>$hnInfo['tenant_goods_money'],
                            "deliver_money"=> "0.00",
                            "discount_money"=> "0.00",
                            "coupon_money"=> "0.00",
                            "tax_difference_money"=> "0.00",
                            "real_total_money"=> $hnInfo['tenant_total_money'],
                            "remark"=> "",
                        ];

                        $_data['order_goods'][] = [
                            "goods_name"=>$hnInfo['goods_name'],
                            "goods_num"=>$hnInfo['goods_num'],
                            "goods_type"=>$_order['trade_type_name'],
                            "goods_img"=> $_order['headImg'],
                            "spec_sku_name"=>$_order['sku_name'],
                            "sku_id"=> $hnInfo['sku_id'],
                            "goods_money"=>$hnInfo['tenant_goods_price'],
                            "goods_spu"=>$hnInfo['goods_spu'],
                            "trade_type_id"=>''
                        ];

                        $express_info = $logisticsModel
                            ->distinct(true)
                            ->field('express_no,express_name,express_code')
//                    ->where('order_id',$_order['orderlistId'])
                            ->where('order_no',$hnInfo['order_no'])
                            ->select();
                        if(empty($express_info)) {
                            $express_info = [];
                        }else{
                            $express_info =  $express_info->toArray();
                            foreach ($express_info as &$info){
                                $info['express_id'] = '';
                                $info['track_info'] = json_encode([]);
                            }
                        }

                        $_data['express_info'] = $express_info;
                        $_data['order_status'] = $hnInfo['mall_order_status'];

//            $_data['api_post_status'] = $_order['api_post_status'];
                        $return[] = $_data;
                    }
                }

            } catch (\Exception $exception) {
                return [ 'code'=>Code::FAILED , 'msg'=> $exception->getMessage()];
            }

            return ['code'=>Code::SUCCESS, 'msg' => 'success','data'=>$return];

        }else{

            try {
                foreach ($order_nos as $key => $order_no){
                    $data = ['order_no'=>$order_no];

                    $result = (new HNOrderApi())->info($data)['data'];

                    $_goods_money = 0;
                    foreach ($result['order_goods'] as &$vv){
                        $rule_money_where = [
                            'order_no'=>$order_no,
                            'goods_spu'=>$vv['goods_spu'],
                            'sku_id'=>$vv['sku_id']
                        ];
                        if($tenant_id != 0){
                            $rule_money_where['tenant_id'] = $tenant_id;
                        }

                        $rule_money = $hnOrderDetailModel->where($rule_money_where)->value('tenant_goods_price');

                        $vv['goods_money'] = $rule_money;
                        $_goods_money += $rule_money * $vv['goods_num'];
                    }

//                "goods_money": "61.50", //商品总额
//                "deliver_money": "0.00", //运费金额
//                "discount_money": "3.00", //优惠金额
//                "coupon_money": "0.00", //优惠券金额
//                "tax_difference_money": "0.00", //税差金额
//                "real_total_money": "58.50", //实付金额
                    unset($result['pay_no']);
                    unset($result['pay_type']);
                    unset($result['pay_time']);
                    unset($result['create_time']);

                    $result['goods_money'] = number_format($_goods_money,2,'.','');
                    $result['real_total_money'] = real_total_money($result['goods_money'], $result['deliver_money'],$result['discount_money'],$result['coupon_money'],$result['tax_difference_money']);

                    $return[$key] = $result;
                }

            } catch (\Exception $exception) {
                return [ 'code'=>Code::FAILED , 'msg'=> $exception->getMessage()];
            }

            return ['code'=>Code::SUCCESS, 'msg' => 'success','data'=>$return];

        }






    }

    //查询订单
    protected function get_info_bak(){
        $request = (new ThinkRequest);
        $params =  $request::post();
        $hnOrderDetailModel = new HnOrderDetail;
        $hnOrderModel = new \catchAdmin\customs\model\Order;
        $externalGoodsRuleModel = new externalGoodsRuleModel;
        $tenant_id = $this->merchantInfo['tenant_id'];

        //dd($params);
        //$order_id = $params['order_id'] ?? '';
        $source_order_no = $params['source_order_no'] ?? '';

        $order_pk = $hnOrderModel->where('tenant_id',$this->merchantInfo['tenant_id'])
            ->where('orderId',$source_order_no)->value('id');

        $order_nos = $hnOrderDetailModel
            ->where('tenant_id',$this->merchantInfo['tenant_id'])
            ->where('order_id',$order_pk)->column('order_no');

        if(empty($order_nos))  return [ 'code'=>Code::FAILED , 'msg'=> '订单不存在或未完成推单'];

        $return = [];
        try {
            foreach ($order_nos as $key => $order_no){
                $data = ['order_no'=>$order_no];

                $result = (new HNOrderApi())->info($data)['data'];

                $_goods_money = 0;
                foreach ($result['order_goods'] as &$vv){
                    $rule_money_where = [
                        'order_no'=>$order_no,
                        'goods_spu'=>$vv['goods_spu'],
                        'sku_id'=>$vv['sku_id']
                    ];
                    if($tenant_id != 0){
                        $rule_money_where['tenant_id'] = $tenant_id;
                    }

                    $rule_money = $hnOrderDetailModel->where($rule_money_where)->value('tenant_goods_price');

                    $vv['goods_money'] = $rule_money;
                    $_goods_money += $rule_money * $vv['goods_num'];
                }

//                "goods_money": "61.50", //商品总额
//                "deliver_money": "0.00", //运费金额
//                "discount_money": "3.00", //优惠金额
//                "coupon_money": "0.00", //优惠券金额
//                "tax_difference_money": "0.00", //税差金额
//                "real_total_money": "58.50", //实付金额
                unset($result['pay_no']);
                unset($result['pay_type']);
                unset($result['pay_time']);
                unset($result['create_time']);

                $result['goods_money'] = number_format($_goods_money,2,'.','');
                $result['real_total_money'] = real_total_money($result['goods_money'], $result['deliver_money'],$result['discount_money'],$result['coupon_money'],$result['tax_difference_money']);

                $return[$key] = $result;
            }

        } catch (\Exception $exception) {
            return [ 'code'=>Code::FAILED , 'msg'=> $exception->getMessage()];
        }

        return ['code'=>Code::SUCCESS, 'msg' => 'success','data'=>$return];
    }

    //取消订单
    protected function cancel(){
        $request = (new ThinkRequest);
        $params =  $request::post();

        //dd($params);

        $order_id = $params['order_id'] ?? '';

        //开始退款查询

        $HNOrderApi = new HNOrderApi;

        try {
            //1.本地根据状态、判断是否可以推款（建议）

            //2.接口查订单详情，判断是否可以退款
            $remote_order_info = $HNOrderApi->info(['order_no'=>$order_id])['data'];
            $order_status = $remote_order_info['order_status'];

            //除了0 待发货状态，其他都不给退款
            if(!in_array($order_status,[0])) throw new Exception('无法取消');

            if(!array_key_exists('precheck',$params) || $params['precheck'] !== 'false'){//只检测返回是否可以退款
                return ['code'=>Code::SUCCESS, 'msg' => '可以取消','data'=> null];
            }

            $cancel =  $HNOrderApi->after_sale_apply([
//                    "order_id": 293, //订单id。订单id和订单编号必传一个
                "order_no"=> $order_id, //订单编号。订单id和订单编号必传一个
                "source_sale_sn"=> "WD" . Str::random(20,1), //售后工单编号
                "post_type"=> 1, //售后类型 1退款，2申请补偿，3退货退款，4换货，5补发
                "refund_reason_id"=> 1, //售后原因id 通过售后原因接口获取
                "num"=> 1, //退款数量
                "refund_description"=>"退款"
            ])['data'];
//            dd($cancel);

//            {
//                 "code": 200,
//              "msg": "提交成功",
//              "data": {
//                            "sale_id": 1407,
//                "post_sale_sn": "OS2023110901407"
//              }
//            }

            return ['code'=>Code::SUCCESS, 'msg' => '提交成功','data'=>$cancel];
        } catch (\Exception $exception) {
            return [ 'code'=>Code::FAILED , 'msg'=> $exception->getMessage()];
        }

        //------如果 precheck = false 直接请求退款接口
        //1.调用退款接口

        //------否则的话

        //3.返回是否可以退款
    }

    //售后详情
    protected function after_sale_detail(){
        $request = (new ThinkRequest);
        $params =  $request::post();

        //dd($params);
        $order_id = $params['order_id'] ?? '';

        $HNOrderApi = new HNOrderApi;

        try {
            $info =  $HNOrderApi->after_sale_detail([
                'order_no'=>$order_id,
            ])['data'];

            return ['code'=>Code::SUCCESS, 'msg' => '提交成功','data'=>$info];
        } catch (\Exception $exception) {
            return [ 'code'=>Code::FAILED , 'msg'=> $exception->getMessage()];
        }
    }
}